package com.taritari.journal.aspect;

import cn.hutool.core.date.DateUtil;
import com.taritari.journal.entity.po.SysLog;
import com.taritari.journal.mapper.SysLogMapper;
import com.taritari.journal.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

import static java.sql.DriverManager.println;

/**
 * @author taritari
 * @date 2023-12-04 20:27
 * @description
 */
@Slf4j
@Component
@Aspect
public class LogAspect{
    @Autowired
    private SysLogMapper sysLogMapper;
    /**
     * 第二步：定义一个切入点，含义：(只对com.dhx..service.*Service.save的方法起作用)
     */
    @Pointcut("execution(* com.taritari.journal.services..*.*(..))")
    public void logPointcut() {}

    /**
     * 第三步：定义处理事件
     * @param joinPoint： 连接点(可以在这个类中获取对应的注解参数和方法参数)
     */
    @Before(value ="logPointcut()")
    public void logTest(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        String declaringTypeName = signature.getDeclaringTypeName();
        String name = signature.getName();
        String currentUser = TokenUtils.getCurrentUser();
        log.info("@Before"+"方法参数：{}",args);
        log.info("@Before"+"调用类名：{}",declaringTypeName);
        log.info("@Before"+"用户：{}", currentUser);
        log.info("@Before"+"方法名称: {}",name);
//        SysLog sysLog = new SysLog();
//        sysLog.setArgs(Arrays.toString(args));
//        sysLog.setDeclaringTypeName(declaringTypeName);
//        sysLog.setUserName(currentUser);
//        sysLog.setVoidName(name);
//        sysLog.setDate(DateUtil.date());
//        sysLogMapper.insert(sysLog);
    }
    /**
     * 返回通知
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "logPointcut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("@AfterReturning"+"返回通知：方法的返回值 : [{}]",ret);
    }

    /**
     * 异常通知
     * @param jp
     * @param ex
     */
    @AfterThrowing(throwing = "ex", pointcut = "logPointcut()")
    public void throwss(JoinPoint jp,Exception ex){
        log.info("@AfterThrowing"+"异常通知：方法异常时执行.....");
        log.info("@AfterThrowing"+"产生异常的方法：[{}]",jp);
        log.info("@AfterThrowing"+"异常种类：[{}]",ex);
    }

    /**
     * 后置通知
     */
    @After("logPointcut()")
    public void after(){
        log.info("@After"+"后置通知.....");
    }
}

